import { http, jsonpToJson, env } from '../../utils/index.js'
import * as echarts from '../../components/ec-canvas/echarts';

let watermark = {
  graphic: [
    {
      type: 'group',
      right: 10,
      bottom: 50,
      z: 100,
      children: [
        {
          type: 'text',
          left: 'center',
          top: 'center',
          z: 100,
          style: {
            fill: 'rgba(0,0,0,0.2)',
            text: '小武计算器',
            font: 'bold 20px sans-serif'
          }
        }
      ]
    }
  ],
}

Page({
  data: {
    selectedTab: 'guzhi',
    fundInfo: {

    },
    chicang: {
      Expansion: '', // 截止日期
      Lists: [], // 持仓明细股票
    },
    ec: {
      lazyLoad: true
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.ecComponent = this.selectComponent('#mychart-dom-line');
    this.code = options.code
    this.getGuZhi()
    this.getChiCang()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    if (this.data.selectedTab == 'guzhi') {
      this.getGuZhi()
    } else {
      this.getLeiJiShouYi()
    }
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  initGuZhiChart() {

  },
  async getGuZhi() {
    let res = await http({
      url: `https://fundmobapi.eastmoney.com/FundMApi/FundVarietieValuationDetail.ashx?FCODE=${this.code}&CustomerNo=&UserId=&Uid=&CToken=&UToken=&MobileKey=&zone=&DATES=&POINTCOUNT=&deviceid=5C1164BA-3D4A-4953-A488-00E47222D4BB&plat=Iphone&AppType=Iphone&product=EFund&version=6.2.5&Serverversion=6.2.5&appversion=6.2.5&_=1628842192861&callback=jsonpgz`
    })
    res = jsonpToJson(res, 8, -1) || {}
    let data = []
    res.Datas && res.Datas.forEach(item => {
      item = item.split(',')
      data.push({ date: item[1], value: item[2] })
    })


    if (!data.length) {
      this.setData({
        noGuZhi: true
      })
      this.ecComponent.init((canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        this.chart = chart;
        return chart
      })
    } else {
      let option = {
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLabel: {
            interval: (data.length - 1) / 2 - 1
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}%'
          },
          splitNumber: 4,
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            type: 'line', name: '估值', symbolSize: 0, smooth: false, lineStyle: {
              width: 1
            }, itemStyle: { color: data[data.length - 1]['value'] > 0 ? 'red' : 'green' }
          },
        ],
        dataset: {
          dimensions: ['date', 'value'],
          source: data
        }
      }
      this.ecComponent.init((canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });

        chart.setOption(option, { notMerge: true })
        this.chart = chart;
        return chart
      })
    }

    if (res.Expansion) {
      this.setData({
        'fundInfo': res.Expansion,
        'selectedTab': 'guzhi'
      })
    } else {
      let res = await http({
        url: `https://fundgz.1234567.com.cn/js/${this.code}.js`,
        method: 'get',
        loading: false
      })
      res = jsonpToJson(res) || {}
      this.setData({
        'fundInfo': {
          SHORTNAME: res.name,
          FCODE: res.fundcode
        },
        'selectedTab': 'guzhi'
      })
    }

  },
  async getPingZhongData() {
    try {
      // 可能会404
      let res = await http({
        url: `http://fund.eastmoney.com/pingzhongdata/${this.code}.js?v=${new Date().getTime()}`,
        method: 'get',
        errorDialog: false
      })
      let values = res.split(';')
      this.pingZhong = JSON.parse(values[8].split('=')[1])
    } catch (e) {
      this.pingZhong = null
    }

    // 没有数据室直接返回空
    if (!this.pingZhong) {
      return null
    }

    let gpRes = await http({
      url: `https://push2.eastmoney.com/api/qt/ulist.np/get?cb=jsonpgz&fltt=2&invt=2&ut=267f9ad526dbe6b0262ab19316f5a25b&fields=f2,f3,f12,f14&secids=${this.pingZhong}&_=1628820758295`
    })
    gpRes = jsonpToJson(gpRes) || {}
    gpRes = gpRes.data && gpRes.data.diff || []

    let result = {}
    gpRes.forEach(gp => {
      result[gp.f12] = gp
    })
    return result
  },
  async getChiCang() {
    let pingZhongInfo = await this.getPingZhongData()
    // 没有持仓明细的数据
    if (!pingZhongInfo) {
      return
    }
    let res = await http({
      url: `https://fundmobapi.eastmoney.com/FundMNewApi/FundMNInverstPosition?FCODE=${this.code}&deviceid=Wap&plat=Wap&product=EFund&version=2.0.0&Uid=&_=`,
      method: 'get'
    })

    res.Datas && res.Datas.fundStocks && res.Datas.fundStocks.forEach(stock => {
      let info = pingZhongInfo[stock.GPDM] || {}
      stock.jg = info['f2'] || '--'
      stock.zdf = info['f3'] || '--'
    })

    this.setData({
      'chicang.Expansion': res.Expansion || '',
      'chicang.Lists': res.Datas.fundStocks
    })
  },
  async getLeiJiShouYi() {
    let res = await http({
      url: `https://uni-fundts.1234567.com.cn/dataapi/fund/FundVPageAcc?INDEXCODE=&CODE=${this.code}&FCODE=${this.code}&RANGE=n&CustomerNo=&UserId=&Uid=&CToken=&UToken=&MobileKey=&zone=&DATES=&POINTCOUNT=&deviceid=&plat=Iphone&AppType=Iphone&product=EFund&version=6.2.5&Serverversion=6.2.5&appversion=6.2.5`
    })
    let data = res.data

    if (!data || !data.length) {
      this.setData({
        noLeiJiShouYi: true
      })
    } else {
      let option = {
        tooltip: {
          trigger: 'axis'
        },
        dataset: {
          dimensions: ['pdate', 'yield', 'indexYield'],
          source: data
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          axisLabel: {
            interval: (data.length - 1) / 2 - 1
          }
        },
        yAxis: {
          type: 'value',
          splitNumber: 3,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            type: 'line', name: '沪深300', symbolSize: 0, smooth: false, lineStyle: { width: 1 }, itemStyle: { color: '#008aff' }
          },
          {
            type: 'line', name: '本基金', symbolSize: 0, smooth: false, lineStyle: { width: 1 }, itemStyle: { color: '#ff4400' }
          },
        ]
      }
      this.chart.setOption(option, { notMerge: true })
    }


    this.setData({
      'selectedTab': 'leijishouyi'
    })
  }
})